package com.xjz.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xjz.annotation.AuthCheck;
import com.xjz.common.BaseResponse;
import com.xjz.common.DeleteRequest;
import com.xjz.common.ResultUtils;
import com.xjz.common.enums.ErrorCode;
import com.xjz.constant.UserConstant;
import com.xjz.exception.BusinessException;
import com.xjz.exception.ThrowUtils;
import com.xjz.model.dto.post.PostAddRequest;
import com.xjz.model.dto.post.PostEditRequest;
import com.xjz.model.dto.post.PostQueryRequest;
import com.xjz.model.dto.post.PostUpdateRequest;
import com.xjz.model.entity.Post;
import com.xjz.model.entity.User;
import com.xjz.model.vo.PostVO;
import com.xjz.service.PostService;
import com.xjz.service.UserService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * ClassName: PostController
 * Package: com.xjz.controller
 * Description:
 *
 * @Author 许小健
 * @Create 2025/8/10 23:27
 * @Version 1.0
 */
@RestController
@RequestMapping("/post")
@Slf4j
public class PostController {
    @Resource
    private PostService postService;

    @Resource
    private UserService userService;

    //region 增删改查

    @PostMapping("/add")
    public BaseResponse<Long> addPost(@RequestBody PostAddRequest postAddRequest, HttpServletRequest request) {
        if (postAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Post post = new Post();
        BeanUtil.copyProperties(postAddRequest, post);
        List<String> tags = postAddRequest.getTags();
        if (CollectionUtil.isNotEmpty(tags)) {
            post.setTags(JSONUtil.toJsonStr(tags));
        }

        //校验
        postService.validPost(post,true);
        User loginUser = userService.getLoginUser(request);
        post.setUserId(loginUser.getId());
        post.setFavourNum(0L);
        post.setThumbNum(0L);
        boolean result = postService.save(post);
        ThrowUtils.throwIf(!result, ErrorCode.OPERRATION_ERROR);
        return ResultUtils.success(post.getId());
    }

    /**
     * 删除
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deletePost(@RequestBody DeleteRequest deleteRequest,HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        User user = userService.getLoginUser(request);
        Long id = deleteRequest.getId();
        Post oldPost = postService.getById(id);
        if (oldPost == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        //仅本人或管理员可以删除
        if (!oldPost.getUserId().equals(user.getId()) && !userService.isAdmin(user)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        boolean result = postService.removeById(id);
        return ResultUtils.success(result);

    }

    /**
     * 更新(仅管理员)
     * @param postUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatePost(@RequestBody PostUpdateRequest postUpdateRequest) {
        if (postUpdateRequest == null || postUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Post post = new Post();
        BeanUtil.copyProperties(postUpdateRequest, post);
        List<String> tags = postUpdateRequest.getTags();
        if (CollectionUtil.isNotEmpty(tags)) {
            post.setTags(JSONUtil.toJsonStr(tags));
        }

        //校验参数
        postService.validPost(post,false);
        Long id = postUpdateRequest.getId();

        //判断是否存在
        Post oldPost = postService.getById(id);
        ThrowUtils.throwIf(oldPost == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = postService.updateById(post);
        return ResultUtils.success(result);
    }

    /**
     * 根据Id获取帖子
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<PostVO> getPostVOById(Long id,HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Post post = postService.getById(id);
        if (post == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(postService.getPostVO(post,request));
    }

    /**
     * 分页获取列表（封装类）
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PostVO>> listPostVOByPage(@RequestBody PostQueryRequest postQueryRequest, HttpServletRequest request) {
        Long current = postQueryRequest.getCurrent();
        Long pageSize = postQueryRequest.getPageSize();

        //限制爬虫
        ThrowUtils.throwIf(pageSize > 20,ErrorCode.PARAMS_ERROR);
        Page<Post> postPage = postService.page(new Page<>(current, pageSize),postService.getQueryWrapper(postQueryRequest));
        return ResultUtils.success(postService.getPostVOPage(postPage,request));

    }

    /**
     * 分页获取当前用户创建的帖子列表
     * @param postQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<PostVO>> listMyPostVOByPage(@RequestBody PostQueryRequest postQueryRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(postQueryRequest == null, ErrorCode.PARAMS_ERROR);

        User loginUser = userService.getLoginUser(request);
        postQueryRequest.setUserId(loginUser.getId());
        Long current = postQueryRequest.getCurrent();
        Long pageSize = postQueryRequest.getPageSize();
        //限制爬虫
        ThrowUtils.throwIf(pageSize > 20,ErrorCode.PARAMS_ERROR);
        Page<Post> postPage = postService.page(new Page<Post>(current, pageSize), postService.getQueryWrapper(postQueryRequest));
        return ResultUtils.success(postService.getPostVOPage(postPage,request));
    }

    //endregion

    /**
     * 分页搜索（从 ES 查询，封装类）
     * @param postQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/search/page/vo")
    public BaseResponse<Page<PostVO>> searchPostVOByPage(@RequestBody PostQueryRequest postQueryRequest,
                                                         HttpServletRequest request) {
        Long size = postQueryRequest.getPageSize();
        //限制爬虫
        ThrowUtils.throwIf(size > 20,ErrorCode.PARAMS_ERROR);
        Page<Post> postPage = postService.searchFromEs(postQueryRequest);
        return ResultUtils.success(postService.getPostVOPage(postPage,request));
    }

    /**
     * 编辑(用户)
     * @param postEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editPost(@RequestBody PostEditRequest postEditRequest,HttpServletRequest request) {
        if (postEditRequest == null || postEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Post post = new Post();
        BeanUtil.copyProperties(postEditRequest, post);
        List<String> tags = postEditRequest.getTags();
        if (CollUtil.isNotEmpty(tags)) {
            post.setTags(JSONUtil.toJsonStr(tags));
        }

        //参数校验
        postService.validPost(post,false);
        User loginUser = userService.getLoginUser(request);
        Long id = postEditRequest.getId();
        //判断是否存在
        Post oldPost = postService.getById(id);
        ThrowUtils.throwIf(oldPost == null, ErrorCode.NOT_FOUND_ERROR);
        //仅本人或管理员可编辑
        if (!oldPost.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        boolean result = postService.updateById(post);
        return ResultUtils.success(result);
    }
}
